package com.xiang.handler;

import com.xiang.entity.UserInfo;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * 服务端回数据
 */
@Slf4j
public class ClientInbandHandler1 extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("ClientInbandHandler1 channelActive ... ");
        //向服务端发送数据
        for (int i = 0; i < 10; i++) {
            UserInfo userInfo =new UserInfo(i,"name"+i);
            //server端 LineBasedFrameDecoder() 解码器
//            ctx.channel().writeAndFlush(ctx.alloc().buffer().writeBytes((userInfo.toString()+"\n").getBytes(StandardCharsets.UTF_8)));
            // DelimiterBasedFrameDecoder 解码器
//            ctx.channel().writeAndFlush(ctx.alloc().buffer().writeBytes((userInfo.toString()+"$").getBytes(StandardCharsets.UTF_8)));
            //header+body 固定长度编解码器
//            ctx.channel().writeAndFlush(ctx.alloc().buffer().writeBytes((userInfo.toString()).getBytes(StandardCharsets.UTF_8)));

            //使用StringEncoder
            ctx.channel().writeAndFlush(userInfo.toString());
            //google protobuf 编解码
//            ctx.channel().writeAndFlush(proto对象);

        }
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("ClientInbandHandler1 channelInactive ... ");
        super.channelInactive(ctx);
    }

    /**
     * 读取server端发送的数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("ClientInbandHandler1 channelRead ... ");
        ByteBuf buf = (ByteBuf) msg;
        byte[] bytes =new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        String serverMsg = new String(bytes, StandardCharsets.UTF_8);
        log.info("Get Server Msg:{}",serverMsg);
        super.channelRead(ctx, msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("ClientInbandHandler1 channelReadComplete ... ");
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.info("ClientInbandHandler1 exceptionCaught ... ");
        super.exceptionCaught(ctx, cause);
    }
}
